/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.core.session;

import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import org.springframework.util.Assert;

/**
 * CAFSession持有者
 * @author wangyandong
 * @date 2019/12/16 18:53
 *
 */
public class CafSessionThreadHolder {
    private static final ThreadLocal<CafSession> threadLocal = new InheritableThreadLocal<>();

    /**
     * 获取当前Session
     * @return
     */
    public static CafSession getCurrentSession() {
        return threadLocal.get();
    }

    /**
     * 设置上下文Session
     * @param session
     */
    public static void setCurrentSession(CafSession session) {
        Assert.notNull(session, "Only non-null CafSession instances are permitted");
        if(session.getSessionType() == SessionType.backend)
            threadLocal.set(session);
    }

    /**
     * 设置上下文Session
     * @param sessionId
     */
    public static void setCurrentSession(String sessionId) {
        Assert.hasText(sessionId, "Only non-null sessionId are permitted");
        ICafSessionService service = SpringBeanUtils.getBean(ICafSessionService.class);
        CafSession session = service.findById(sessionId);
        //设置到当前上下文
        CafSessionThreadHolder.setCurrentSession(session);
    }

    /**
     * 清空上下文session
     */
    public static void purge() {
        threadLocal.remove();
    }
}
